use crate::db::connector::get_connection;
use crate::db::read::FilterBuilder;
use crate::error::AppError;
use crate::schemas::base::FilterItem;
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, QueryFilter};
use std::str::FromStr;

impl<E: EntityTrait> FilterBuilder<E> for sea_orm::DeleteMany<E> {}

pub async fn by_filter<Entity, ActiveModel>(
    db_identifier: &str,
    filters: Option<Vec<FilterItem>>,
) -> crate::error::Result<(), AppError>
where
    Entity: EntityTrait,
    ActiveModel: ActiveModelTrait<Entity = Entity> + Send + 'static + sea_orm::ActiveModelBehavior,
{
    let db = get_connection(db_identifier)?;
    let mut executor = Entity::delete_many();
    if let Some(filters) = filters {
        executor = executor.apply_filters(filters)?
    };
    executor.exec(&db).await?;
    Ok(())
}

pub async fn by_id<Entity, ActiveModel>(
    db_identifier: &str,
    id: String,
) -> crate::error::Result<String, AppError>
where
    Entity: EntityTrait,
    ActiveModel: ActiveModelTrait<Entity = Entity> + Send + 'static + sea_orm::ActiveModelBehavior,
{
    let db = get_connection(db_identifier)?;
    let mut executor = Entity::delete_many();
    let column_enum = Entity::Column::from_str("id")
        .map_err(|_| AppError::Custom(format!("Invalid field '{}'.", "id")))?;
    executor = executor.filter(column_enum.eq(id.to_owned()));
    executor.exec(&db).await?;
    Ok(id)
}
